<template>
  <view id="car" class="u-skeleton">
    <view class="car">
      <swiper :class="['u-skeleton-fillet']" />

      <view v-if="list.length == 0" class="not-goods">
        <u-empty text="购物车，空空如也..." mode="car"></u-empty>
      </view>
      <view :style="{ marginTop: '20rpx' }">
        <u-checkbox-group
          :wrap="true"
          shape="circle"
          active-color="#D65C45"
          v-if="list.length > 0"
        >
          <view
            class="foods-list boxShadow u-skeleton-fillet"
            v-for="(item, index) in list"
            :key="index"
          >
            <u-checkbox
              v-model="item.value"
              @change="change"
              :name="item.goods_item_id"
            >
              <view class="foods-info">
                <image :src="item.item_pic" class="image" />

                <view class="foods-detail">
                  <view>
                    <view class="foods-title u-line-2">{{
                      item.item_title
                    }}</view>
                    <view class="foods-stock">库存：{{ item.storage }}</view>
                  </view>
                  <view class="foods-price-car">
                    <view class="foods-price">
                      <view>￥{{ item.price / 100 }}</view>
                      <view>￥{{ item.market_price / 100 }}</view>
                    </view>
                    <view class="buy-num">
                      <view
                        class="iconfont icon-jian jian"
                        @click.stop="reduceBuyCount(item, index)"
                      ></view>
                      <view class="num">{{ item.number }}</view>
                      <view
                        class="iconfont icon-add-fill jia"
                        @click.stop="addByCount(item, index)"
                      ></view>
                    </view>
                  </view>
                </view>
              </view>
            </u-checkbox>
          </view>
        </u-checkbox-group>
      </view>
    </view>
    <!-- 底部 -->
    <view class="car-bottom u-skeleton-fillet" v-if="list.length > 0">
      <view @click="chooseAll">
        <view class="circle">
          <image v-show="isChooseAll" src="@/static/shop/choose.png" />
        </view>
        <view>全选</view>
      </view>
      <view>
        <view class="price">￥{{ totalMoney / 10000 }}</view>
        <view class="num">共计{{ totalNumber }}件</view>
      </view>
      <view @click="$u.debounce(submit, 1000)">结算</view>
    </view>

    <u-top-tips ref="uTips"></u-top-tips>
    <!--引用组件-->
    <u-skeleton
      :loading="loading"
      :animation="true"
      bgColor="#FFF"
    ></u-skeleton>
    <u-mask :show="show"></u-mask>
  </view>
</template>

<script>
import Swiper from "@/common/components/swiper";
import { orderStatusCheck } from "@/common/utils";
export default {
  components: {
    Swiper,
  },
  data() {
    return {
      loading: true,
      show: false,
      value: "",
      totalMoney: 0,
      totalNumber: 0,
      merchant_id: 0, //店铺id
      isChooseAll: true,
      list: [{}, {}, {}, {}],
    };
  },
  watch: {
    list: {
      handler(newV, oldV) {
        this.totalMoney = 0;
        this.totalNumber = 0;
        // 购物车没有
        if (this.list === [] || this.list === null) {
          this.totalMoney = 0;
          this.totalNumber = 0;
          return;
        }
        console.log(this.list);
        //  重新计算 总价格
        this.list.map((v) => {
          if (v.value) {
            this.totalMoney += parseFloat(v.number * v.price * 100);
            this.totalNumber += parseInt(v.number);
          }
        });
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    /**
     * 订单提交
     */
    submit() {
      this.show = true;
      uni.showLoading({
        title: "订单提交中",
      });
      var form = {
        merchant_id: this.merchant_id,
        goods_list: [],
      };
      this.list.map((v) => {
        if (v.value) {
          var form1 = {
            goods_id: v.goods_id,
            goods_item_id: v.goods_item_id,
            number: v.number,
          };
          form.goods_list.push(form1);
        }
      });
      this.$u.api
        .orderSubmitApi(form)
        .then((res) => {
          this.orderPayApi(res);
        })
        .catch((error) => {
          if (error.code === 1002) {
            this.$u.toast(error.message);
            setTimeout(() => {
              uni.switchTab({
                url: "/pages/center/center",
              });
            }, 1000);
          }
        });
    },
    /**
     * 订单支付
     */
    orderPayApi(res) {
      var _this = this;
      var form = {
        ordersn: res.ordersn,
      };
      this.$u.api.orderPayApi(form).then((res) => {
        //小程序发起微信支付
        uni.requestPayment({
          provider: "wxpay",
          timeStamp: res.timeStamp.toString(),
          nonceStr: res.nonce_str,
          package: "prepay_id=" + res.prepay_id,
          signType: res.sign_type,
          paySign: res.sign,
          success: function (res) {
            _this.show = false;
            // 订单状态处理
            orderStatusCheck(form.ordersn);
          },
          fail: function (err) {
            _this.$u.vuex("vuex_car_list", []);
            uni.reLaunch({
              url: "/pages/myfoods/myfoods?router=1",
            });
          },
          complete: function () {},
        });
      });
    },
    /**
     * 全选
     */
    chooseAll() {
      if (this.isChooseAll) {
        this.list.map((v) => {
          v.value = false;
        });
        this.isChooseAll = false;
      } else {
        this.list.map((v) => {
          v.value = true;
        });
        this.isChooseAll = true;
      }
    },

    /**
     * 减少库存
     */
    reduceBuyCount(item, index) {
      var _this = this;
      if (parseInt(this.list[index].number) >= 2) {
        this.list[index].number = parseInt(this.list[index].number) - 1;
      } else {
        uni.showModal({
          title: "删除",
          content: "确定移除购物车？",
          success(res) {
            if (res.confirm) {
              var form = {
                merchant_id: _this.merchant_id,
                goods_list: [
                  {
                    goods_id: item.goods_id,
                    goods_item_id: item.goods_item_id,
                    number: 0,
                  },
                ],
              };
              _this.deleteGoods(form, index);
            }
          },
        });
      }
    },
    /**
     * 删除商品
     */
    deleteGoods(from, index) {
      this.list.splice(index, 1);
      this.$u.api.setCarApi(from).then((res) => {
        // this.getCarData();
        // tips
        this.$refs.uTips.show({
          title: "移除成功",
          type: "error",
          duration: "500",
        });
      });
    },
    /**
     * 增加库存
     */
    addByCount(item, index) {
      if (this.list[index].storage > parseInt(this.list[index].number)) {
        this.list[index].number = parseInt(this.list[index].number) + 1;
      } else {
        this.$u.toast("库存不足");
      }
    },

    /**
     * checkBox改变
     */
    change(e) {
      console.log(e);
      if (!e.value) {
        this.isChooseAll = false;
      }
      this.totalMoney = 0;
      this.totalNumber = 0;
      //  重新计算 总价格
      this.list.map((v) => {
        if (v.value) {
          this.totalMoney += parseFloat(v.number * v.price * 100);
          this.totalNumber += parseInt(v.number);
        }
      });
    },
    /**
     * 获取购物车信息
     *
     */
    getCarData() {
      this.list = [];
      this.$u.api
        .getCarDataApi({ merchant_id: this.merchant_id })
        .then((res) => {
          this.list = res.list;
          this.list.map((v) => {
            v.value = true;
          });
          this.loading = false;
        });
    },
  },
  onShow() {
    this.getCarData();
    this.show = false;
  },
  onLoad(option) {
    this.merchant_id = option.merchant_id;
  },
};
</script>

<style scoped lang ='scss' >
@mixin flex-row {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.car {
  min-height: calc(100vh - 100rpx);
  padding: 30rpx;
  background-color: #f7f7f7;
  padding-bottom: 150rpx;
  .not-goods {
    margin-top: 200rpx;
  }
  .foods-list {
    height: 230rpx;
    margin-bottom: 20rpx;
    background-color: #ffffff;
    line-height: 230rpx;
    border-radius: 20rpx;
    padding: 20rpx;
    @include flex-row;
    .foods-info {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      .image {
        width: 140rpx;
        height: 140rpx;
        margin-top: 16rpx;
        margin-right: 20rpx;
        margin-left: 10rpx;
      }
      .foods-detail {
        width: 430rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: flex-start;

        .foods-price-car {
          width: 100%;
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
          .buy-num {
            @include flex-row;
            .jian {
              color: #dcdcdc;
              font-size: 48rpx;
              margin-right: 20rpx;
            }
            .jia {
              color: #d65c45;
              font-size: 50rpx;
              margin-left: 20rpx;
            }
            .num {
              color: #333333;
              font-size: 28rpx;
              font-weight: bold;
            }
          }
          .add-car {
            color: #d65c45;
            font-size: 48rpx;
          }
          .foods-price {
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            align-items: center;
            & > view:nth-child(1) {
              font-size: 32rpx;
              color: #d65c45;
              margin-right: 10rpx;
            }
            & > view:nth-child(2) {
              font-size: 24rpx;
              color: #999999;
              text-decoration: line-through;
            }
          }
        }
        .foods-title {
          font-size: 30rpx;
          color: #333333;
          font-weight: bold;
          margin-top: 40rpx;
        }
        .foods-stock {
          /* margin: 10rpx 0; */
          color: #333333;
        }
      }
    }
  }
}
.car-bottom {
  @include flex-row;
  height: 150rpx;
  width: 100vw;
  background-color: #ffffff;
  border-top: 1rpx solid #e6e6e6;
  position: fixed;
  bottom: 0;
  & > view:nth-child(1) {
    margin-left: 40rpx;
    @include flex-row;
    width: 100rpx;
    color: #333333;
    font-size: 28rpx;
    .circle {
      width: 32rpx;
      height: 32rpx;
      line-height: 32rpx;
      text-align: center;
      border-radius: 50%;
      border: 1rpx solid #cccccc;
      & > image {
        width: 100%;
        height: 100%;
      }
    }
  }
  & > view:nth-child(2) {
    flex: 1;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    align-items: center;
    .price {
      color: #d65c45;
      font-size: 32rpx;
      font-weight: blod;
      margin-right: 20rpx;
    }
    .num {
      font-size: 24rpx;
      color: #333333;
    }
  }
  & > view:nth-child(3) {
    background-color: #d65c45;
    width: 240rpx;
    height: 100%;
    text-align: center;
    line-height: 150rpx;
    color: #ffffff;
    font-weight: bold;
    font-size: 28rpx;
    margin-left: 20rpx;
  }
}
</style>
